class WeatherController < ApplicationController
  require('helpers/classes/xml_element_wrapper.rb')
  
  layout nil
     
  def show_short
    @days_total = 1;
    load
  end
  
  def show_4day
    @days_total = 4;
    load
  end
  
  protected
  def load
      # config keys
      @zip          = "IDXX0032" # loc_id for mataram, lombok, indonesia
      @par_id       = "1036260301"
      @weather_key  = "aa4e5c49f450d1eb"
      
      @w = Weather.find :first, :order => 'id desc'
      # check if it is nil, when so => create new 
      @w = Weather.new if @w == nil
      
      # should we update, when nil or when last update one hour ago
      if @w.new_record? ||  ((Time.now - @w.created_at)/60) > 60 || @w.weather_xml == nil
        # get the response
        begin
           response = Net::HTTP.get_response("xoap.weather.com",
                    "/weather/local/#{@zip}?cc=*&unit=m&dayf={@days_total}" + 
                    "&prod=xoap&par=#{@par_id}&key=#{@weather_key}")
                    
           @w.weather_xml = response.body
           @w.created_at = Time.now
           @w.save()
           
        rescue SocketError
          render :text => "Weather not available"
          return
        end 
      end
      
      # load into wrapper
      @weather = XMLElementWrapper.new(REXML::Document.new(@w.weather_xml).root)
  end
  
end
